package org.jeecg.modules.friends.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.digest.DigestUtils;

public class MD5Utils
{
    /**
     * MD5加密之方法一
     *
     * @explain 借助apache工具类DigestUtils实现
     * @param str 待加密字符串
     * @return 16进制加密字符串
     */
    public static String encryptToMD5(String str)
    {
        return DigestUtils.md5Hex(str);
    }
    public static String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * MD5加密之方法一
     *
     * @explain 借助apache工具类DigestUtils实现
     * @param file 待加密文件
     * @return 16进制加密字符串
     * @throws IOException
     */
    public static String encryptToMD5(File file)
            throws IOException
    {
        try (InputStream fis = new FileInputStream(file))
        {
            return DigestUtils.md5Hex(fis);
        }
    }

    /**
     * MD5加密之方法二
     *
     * @explain spring实现
     * @param str 待加密字符串
     * @return 16进制加密字符串
     */
    public static String encrypt2ToMD5(String str)
    {
        return org.springframework.util.DigestUtils.md5DigestAsHex(str.getBytes(Charsets.UTF_8));
    }

    /**
     * MD5加密之方法二
     *
     * @explain spring实现
     * @param file 待加密文件
     * @return 16进制加密字符串
     * @throws IOException
     */
    public static String encrypt2ToMD5(File file)
            throws IOException
    {
        try (InputStream fis = new FileInputStream(file))
        {
            return org.springframework.util.DigestUtils.md5DigestAsHex(fis);
        }
    }
}

